import moduleStore from '@/store/module';
import { createStoreBindings } from '@/miniprogram_npm/mobx-miniprogram-bindings/index';

import tools from '@/utils/tools';
import { getStockPrediction } from '@/service/api/predict';
import { initChart, candlestickChartOption, turnoverChartOption } from '@/utils/echart';

import Message from 'tdesign-miniprogram/message/index';
const messageDefaultConfig = (content) => {
    return {
        content: content,
        offset: [60, 32],
        duration: 2000
    };
};

const stockPickerOption = [
    {
        value: 'moutai',
        label: '贵州茅台'
    },
    {
        value: 'icbc',
        label: '工商银行'
    },
    {
        value: 'catl',
        label: '宁德时代'
    }
];
const categoryPickerOption = [
    {
        value: 'price',
        label: '股价走势'
    },
    {
        value: 'turnover',
        label: '成交量'
    }
];
const stepPickerOption = [
    {
        value: 7,
        label: '未来七日'
    },
    {
        value: 15,
        label: '未来十五日'
    },
    {
        value: 30,
        label: '未来一个月'
    }
];

const getChartOption = (data, category) => {
    const xData = [],
        yData = [];
    let yMin = Infinity;
    data.forEach((item) => {
        xData.push(item.date);
        switch (category) {
            case 'price': {
                yData.push([item.openPri, item.closePri, item.highPri, item.lowPri]);
                yMin = Math.min(yMin, item.lowPri);
                break;
            }
            case 'turnover': {
                yData.push(item.dealNum);
                yMin = Math.min(yMin, item.dealNum);
            }
        }
    });
    if (category == 'price') {
        return candlestickChartOption(xData, yData, Math.ceil((yMin - yMin / 100) * 10) / 10);
    } else {
        return turnoverChartOption(xData, yData, yMin);
    }
};

let myChart;

Page({
    data: {
        stockPickerOption,
        categoryPickerOption,
        stepPickerOption,
        name: 'moutai',
        category: 'price',
        step: 7,
        chartVisable: true,
        ec: {
            onInit: initChart
        }
    },

    onLoad() {
        this.storeBindings = createStoreBindings(this, {
            store: moduleStore,
            actions: ['getStockData', 'getLoadedStock']
        });
    },

    onUnload() {
        this.storeBindings.destroyStoreBindings();
    },

    async handleResetChart() {
        try {
            // 检查全局存储中是否有数据
            if (!this.getLoadedStock()) {
                // 通过接口获取数据
                await getStockPrediction(this.data.name);
            }
			const data = this.getStockData(this.data.name, this.data.step);
            if (!myChart) return;
            myChart.clear();
            myChart.setOption(getChartOption(data, this.data.category));
        } catch (err) {
            Message.error(messageDefaultConfig(err.message));
        }
    },

    onPullDownRefresh: tools.throttle(async function () {
        await getStockPrediction(this.data.name);
        const data = this.getStockData(this.data.name, this.data.step);
        myChart.setOption(getChartOption(data, this.data.category));
    }, 10000),

    async onReady() {
        this.handleResetChart();
    },

    chartInitFinish(e) {
        myChart = e.detail;
        this.handleResetChart();
    },

    operateDropdown(e) {
        if (e.type == 'close') {
            setTimeout(() => {
                this.setData({
                    chartVisable: true
                });
            }, 200);
        }
        this.setData({
            chartVisable: false
        });
    },

    async handleStockChange(e) {
        this.setData({
            name: e.detail.value
        });
        await this.handleResetChart();
    },

    async handleCategoryChange(e) {
        this.setData({
            category: e.detail.value
        });
        await this.handleResetChart();
    },

    async handleStepChange(e) {
        this.setData({
            step: e.detail.value
        });
        await this.handleResetChart();
    }
});
